import type { ToastIcon } from "@/type/type";

export const formatTime = (date: Date): string => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();

    return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`;
}

const formatNumber = (n: number): string => {
    let s = n.toString();
    return s[1] ? s : `0${s}`;
}



const TitleMap: Record<ToastIcon, string> = {
	"success": "成功",
	"error": "失败",
	"loading": "加载中...",
	"none": "",
}
export const showToast = (title: string, icon: ToastIcon, duration: number = 1500, mask: boolean = false) => {
	uni.showToast({
		title: `${title}${TitleMap[icon]}`,
		icon,
		duration,
		mask
	})
}


// 防抖
export function debounce<T extends (...args: any[]) => any>(fn: T, delay: number): (...args: Parameters<T>) => void {
	let timer: ReturnType<typeof setTimeout> | null;
	
	return function(this: ThisParameterType<T>,...args: Parameters<T>) {
		if (timer) {
			clearTimeout(timer)
		}
		timer = setTimeout(() => {
			fn.apply(this, args);
		}, delay);
	};
}
 
// 节流
export function throttle<T extends (...args: any[]) => any>(fn: T, interval: number): (...args: Parameters<T>) => void  {
	let lastTime = 0;
	return function(this: ThisParameterType<T>,...args: Parameters<T>) {
		const now = Date.now();
		if (now - lastTime >= interval) {
			lastTime = now;
			fn.apply(this, args);
		}
	}
}


/**
 * 生成指定长度的随机字符串
 * @param length 字符串长度
 * @returns 随机字符串
 */
export function generateRandomString(length: number): string {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';

  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * chars.length);
    result += chars[randomIndex];
  }

  return result;
}

/**
 * 格式化时间为mm:ss
 * @param {number} second 时间秒 
 * @return 时间字符串
 */ 
export function formatTimeMMSS(second: number): string {
	return new Date(second * 1000).toISOString().substring(14, 19);
}

/**
 * 生成指定范围内的随机整数（包含min和max）
 * @param min 最小值
 * @param max 最大值
 * @returns 范围内的随机整数
 */
export function getRandomInt(min: number, max: number): number {
	return Math.floor(Math.random() * (max - min)) + min;
}